package sort_algorithms;

import main.SortDemo;

import datastructures.Datum;
import datastructures.Status;

/**
 * <p>
 * BubbleSort as deduced from observing the program IITSort v1.0.0
 * </p>
 * 
 * <p>
 * There are still a couple of observed differences between the IIT edition and this...
 * </p>
 * 
 * @author kf6kjg
 */
public class BubbleSortIIT extends AbstractSorter {
  private int   left;
  
  private int   right;
  
  private Datum datum_left;
  
  private Datum datum_right;
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.ISorter#step()
   */
  @Override
  public void step() {
    this.datum_right.status = this.datum_left.status = Status.DEFAULT;
    
    this.datum_left = SortDemo.data.get(this.right - 1);
    this.datum_right = SortDemo.data.get(this.right);
    
    SortDemo.data.get(this.left).status = Status.COMPARE_LEFT;
    this.datum_right.status = Status.COMPARE_RIGHT;
    
    if (this.datum_left.compareTo(this.datum_right) > 0) {
      // Swap the elements
      SortDemo.data.setElementAt(this.datum_right, this.right - 1);
      SortDemo.data.setElementAt(this.datum_left, this.right);
    }
    
    this.right--;
    
    if (this.left >= this.right) {
      this.left++;
      this.right = SortDemo.data.size() - 1;
    }
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.AbstractSorter#isSorted()
   */
  @Override
  public boolean isSorted() {
    if (this.left >= SortDemo.data.size() - 1) {
      SortDemo.data.get(this.left - 1).status = this.datum_right.status = Status.DEFAULT;
      
      return true;
    }
    
    return false;
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.AbstractSorter#getName()
   */
  @Override
  public String getName() {
    return "Bubble Sort - IIT";
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.AbstractSorter#reset()
   */
  @Override
  public void reset() {
    this.left = 0;
    this.right = SortDemo.data.size() - 1;
    
    this.datum_left = SortDemo.data.get(this.right - 1);
    this.datum_right = SortDemo.data.get(this.right);
  }
}
